package com.pw.study.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: linux_future
 * @since: 2022/3/24
 **/
public class TcpServer {

    private boolean started = false;
    private List<ChatThread> chatThreads = new ArrayList<ChatThread>();
    public static void main(String[] args) {
        new TcpServer().startServer();
    }
    private void startServer(){
        try {
            //开启服务端Socket
            ServerSocket serverSocket = new ServerSocket(8888);
            started = true;
            while(started){
                //接受客户端连接请求
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已连接");
                //开启线程处理客户端通信
                ChatThread chatThread = new ChatThread(socket);
                chatThreads.add(chatThread);
                new Thread(chatThread).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private class ChatThread implements Runnable{
        private Socket socket;
        private DataInputStream dataInputStream =null;
        private DataOutputStream dataOutputStream =null;
        private boolean isConnected = false;
        OutputStream outputStream =null;
        PrintWriter printWriter =null;
        public ChatThread(Socket socket) {
            super();
            this.socket = socket;
        }
        //发送信息
        private void send(String strMsgIn){
            try{
                dataOutputStream.writeUTF(strMsgIn);
                dataOutputStream.flush();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            try{
                dataInputStream = new DataInputStream(socket.getInputStream());
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                //读取数据
                isConnected = true;
                while(isConnected){

                    String strMsgIn= dataInputStream.readUTF();

                    System.out.println(strMsgIn);
                    //接收到数据后发送给每个客户端
                    for(int i =0;i<chatThreads.size();i++){
                        chatThreads.get(i).send(strMsgIn);
                    }
                }
            }catch (IOException e) {
                try {
                    //如果客户端出错或关闭，直接关闭连接，并移除List中的当前线程
                    socket.close();
                    chatThreads.remove(this);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } finally{
                try {
                    dataInputStream.close();
                    dataOutputStream.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
